<template>
    <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
        textAlign: 'center',
        background: '#f5f7fa',
        fontWeight: 'bold',
        position: 'sticky',
        top: 0
    }" :span-method="objectSpanMethod">
        <el-table-column fixed width="180px" prop="sale_order_code" label="订单编号">
            <template #default="scope">
                <el-link type="primary" @click="infoPage(scope.row.sale_order_code)">{{ scope.row.sale_order_code
                    }}</el-link>
            </template>
        </el-table-column>
        <el-table-column fixed width="180px" prop="sale_order_audit_status" label="订单状态" />
        <el-table-column prop="customer_name" label="客户名称" width="180px" />
        <el-table-column prop="sale_order_name" label="订单名称" width="180px" />
        <el-table-column prop="pro_name" label="产品名称" width="160px" />
        <el-table-column prop="pro_code" label="产品编号" width="180px" />
        <el-table-column prop="pro_brand" label="品牌" width="150px" />
        <el-table-column prop="pro_model" width="180px" label="规格型号" />
        <el-table-column prop="measure_id" label="单位">
            <template #default="scope">
                <span>{{ measureValue(scope.row.measure_id) }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="pro_sale_qty" width="100px" label="销售数量" />
        <el-table-column prop="sale_order_total_qty" label="销售总数量" width="150px" />
        <el-table-column prop="sale_order_total_price" label="销售总金额" width="150px" />
        <el-table-column prop="sale_order_sign_time" label="订单签订日期" width="190px" />
        <el-table-column prop="sale_order_deliver_time" label="订单交付日期" width="190px" />
    </el-table>
    <div class="pagination-wrapper">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
            :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
</template>

<script>
import axios from 'axios'
import { ref, reactive, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
export default {
    props: {
        detailsData: {
            type: String,
            required: true
        },
        orderCode: String
    },
    setup(props) {
        const tableData = ref([])
        const measureOptios = ref([])
        const currentPage = ref(1)
        const pageSize = ref(5)
        const pageCount = ref(0)
        const store = useStore()
        const router = useRouter()

        onMounted(() => {
            getMeasure()
            fill()
            count()
        })

        // 数据转换方法
        const transformOthwrData = (responseData) => {
            const result = []

            responseData.forEach((mainItem) => {

                // 安全处理日期
                const signTime = mainItem.sale_order_sign_time
                    ? mainItem.sale_order_sign_time.replace('T', ' ')
                    : '';

                const deliverTime = mainItem.sale_order_deliver_time
                    ? mainItem.sale_order_deliver_time.replace('T', ' ')
                    : '';

                mainItem.details.forEach((detail) => {
                    let auditStatusText = '';
                    // 1. 优先判断审核状态：是否为待审核？
                    if (mainItem.sale_order_audit_status === '0') {
                        auditStatusText = '待审核';
                    }
                    // 2. 非待审核时，显示出库状态
                    else if (mainItem.sale_order_audit_status != '0') {
                        switch (mainItem.sale_order_status) {
                            case 0:
                                auditStatusText = '待出库';
                                break;
                            case 1:
                                auditStatusText = '部分出库';
                                break;
                            case 2:
                                auditStatusText = '全部出库';
                                break;
                            default:
                                auditStatusText = '未知出库状态'; // 兜底处理
                        }
                    }
                    // 3. 其他审核状态（通过/驳回）
                    else {
                        switch (mainItem.sale_order_audit_status) {
                            case '1':
                                auditStatusText = '审核通过';
                                break;
                            case '2':
                                auditStatusText = '审核驳回';
                                break;
                            default:
                                auditStatusText = '未知审核状态'; // 兜底处理
                        }
                    }
                    result.push({
                        sale_order_audit_status: auditStatusText,
                        sale_order_id: mainItem.sale_order_id,
                        sale_order_code: mainItem.sale_order_code,
                        customer_name: mainItem.customer_name,
                        sale_order_name: mainItem.sale_order_name,
                        pro_name: detail.pro_name,
                        pro_code: detail.pro_code,
                        pro_brand: detail.pro_brand,
                        pro_model: detail.pro_model,
                        measure_id: detail.measure_id,
                        pro_sale_qty: detail.pro_sale_qty,
                        sale_order_total_qty: mainItem.sale_order_total_qty,
                        sale_order_total_price: mainItem.sale_order_total_price,
                        sale_order_sign_time: signTime,
                        sale_order_deliver_time: deliverTime,
                    })
                })
            })

            return result
        }

        // 合并单元格逻辑（添加空值检查）
        const objectSpanMethod = ({ row, column, rowIndex }) => {
            // 确保有数据
            if (!tableData.value || tableData.value.length === 0) {
                return { rowspan: 1, colspan: 1 };
            }

            // 需要合并的字段
            const fieldsToMerge = [
                'sale_order_code',
                'sale_order_audit_status',
                'customer_name',
                'sale_order_name',
                'sale_order_total_qty',
                'sale_order_total_price',
                'sale_order_sign_time',
                'sale_order_deliver_time',
            ];

            // 不需要合并的列直接返回
            if (!fieldsToMerge.includes(column.property)) {
                return { rowspan: 1, colspan: 1 };
            }

            // 使用订单编号作为分组依据
            const currentGroup = row.sale_order_code;

            // 情况1：当前行是表格第一行 或 与前一行不属于同一订单
            if (rowIndex === 0 || tableData.value[rowIndex - 1].sale_order_code !== currentGroup) {
                let spanCount = 1;

                // 向后查找相同订单的行数
                while (
                    rowIndex + spanCount < tableData.value.length &&
                    tableData.value[rowIndex + spanCount].sale_order_code === currentGroup
                ) {
                    spanCount++;
                }

                // 如果是操作列，需要特殊处理（合并所有同订单的行）
                if (column.property === 'action') {
                    return { rowspan: spanCount, colspan: 1 };
                }

                // 其他合并列检查值是否相同
                let sameValueCount = 1;
                while (
                    rowIndex + sameValueCount < tableData.value.length &&
                    tableData.value[rowIndex + sameValueCount].sale_order_code === currentGroup &&
                    tableData.value[rowIndex + sameValueCount][column.property] === row[column.property]
                ) {
                    sameValueCount++;
                }

                return sameValueCount > 1
                    ? { rowspan: sameValueCount, colspan: 1 }
                    : { rowspan: 1, colspan: 1 };
            }
            // 情况2：与前一行同订单且同值，需要隐藏单元格
            else if (
                tableData.value[rowIndex - 1].sale_order_code === currentGroup &&
                tableData.value[rowIndex - 1][column.property] === row[column.property]
            ) {
                return { rowspan: 0, colspan: 0 };
            }
            // 情况3：同订单内新值的起始位置
            else {
                let sameValueCount = 1;

                while (
                    rowIndex + sameValueCount < tableData.value.length &&
                    tableData.value[rowIndex + sameValueCount].sale_order_code === currentGroup &&
                    tableData.value[rowIndex + sameValueCount][column.property] === row[column.property]
                ) {
                    sameValueCount++;
                }

                return sameValueCount > 1
                    ? { rowspan: sameValueCount, colspan: 1 }
                    : { rowspan: 1, colspan: 1 };
            }
        };

        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        function fill() {
            console.info(props.detailsData)
            axios.get("http://localhost:5181/api/Sinv_Sale_Order/GetSinv_Sale_Infos", {
                params: {
                    currendPage: currentPage.value,
                    pageSize: pageSize.value,
                    customerName: props.detailsData,
                    orderCode: "",
                    orderStatus: -1,
                    auditStatus: '1'
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                tableData.value = transformOthwrData(result.data)
                console.info(tableData.value)
            }).catch((err) => {
                console.info(err)
            });
        }

        function count() {
            axios.get("http://localhost:5181/api/Sinv_Sale_Order/Sinv_Sale_OrderCOunt", {
                params: {
                    customerName: props.detailsData,
                    orderCode: ""
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                pageCount.value = result.data
            }).catch((err) => {
                console.info
            });
        }

        function handleSizeChange(val) {
            pageSize.value = val;
            fill();
        }

        function handleCurrentChange(val) {
            currentPage.value = val;
            fill();
        }

        function infoPage(row) {
            store.commit("SalesOrderCode", row)
            router.push("/main/Sinv/SalesOrdereInfo")
        }

        return {
            tableData,
            transformOthwrData,
            objectSpanMethod,
            measureOptios,
            measureValue,
            currentPage,
            pageSize,
            pageCount,
            handleSizeChange,
            handleCurrentChange,
            infoPage
        }
    }
}
</script>
<style scoped>
.pagination-wrapper {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    margin-top: 20px;
    /* 与表格的间距 */
}
</style>